package com.simple.base.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.simple.util.common.ErrorUtil;


public class CharacterEncodingFilter implements Filter {
	public static final String UTF8_ENCODE = "UTF-8";

	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;

		chain.doFilter(new CharacterEncodingRequest(request), response);
	}

	public void destroy() {

	}

}


class CharacterEncodingRequest extends HttpServletRequestWrapper {
	private static final Logger LOG = Logger
			.getLogger(CharacterEncodingRequest.class);

	public CharacterEncodingRequest(HttpServletRequest request) {
		super(request);
	}

	
	@Override
	public String getParameter(String name){
		String rtn = null;
		try {
			final String value = super.getParameter(name);
			if(null != value){
				rtn = new String(value.getBytes("ISO-8859-1"), CharacterEncodingFilter.UTF8_ENCODE);
			}
		} catch (UnsupportedEncodingException e) {
			LOG.error(ErrorUtil.generateStackTraceString(e));
		}
		return rtn;
	}
	
	@Override
	public String[] getParameterValues(String name){
		String[] rtn = null;
		try {
			final String[] value = super.getParameterValues(name);
			if(null != value){
				rtn = new String[value.length];
				for(int i=0;i<value.length;i++){
					rtn[i] = new String(value[i].getBytes("ISO-8859-1"), CharacterEncodingFilter.UTF8_ENCODE);
				}
			}
		} catch (UnsupportedEncodingException e) {
			LOG.error(ErrorUtil.generateStackTraceString(e));
		}
		return rtn;
	}


}
